package com.offcn.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.offcn.user.dao.UserMapper;
import com.offcn.user.pojo.User;
import com.offcn.user.service.UserService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {

    @Autowired(required = false)
    private UserMapper userMapper;

//    @Autowired
//    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void add(User user) {
        user.setCreated(new Date());
        user.setUpdated(new Date());
        // 密码加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        // 即使明文是相同，但是每次生成的密码是不同的
        String password = encoder.encode(user.getPassword());

        user.setPassword(password);
        userMapper.insert(user);

    }

    @Override
    public void createSmsCode(String phone) {
        String code = new Random().nextInt(900000) + 100000 + "";
        System.out.println("验证码:" + code);  // 生产过程中
        // 存入到缓存中
        stringRedisTemplate.boundHashOps("smscode").put(phone,code);
        // 发送到 MQ 中
        HashMap<String, String> info = new HashMap<>();
        info.put("phone",phone);
        info.put("code",code);
        rabbitTemplate.convertAndSend("dongyimai.sms.queue",info);
    }

    @Override
    public boolean checkSmsCode(String phone, String code) {
        // 根据用户填入的手机号获取 存储的 codeFromRedis
        String codeFromRedis = (String)stringRedisTemplate.boundHashOps("smscode").get(phone);

        if (codeFromRedis == null){
            return false;
        }
        if(codeFromRedis.equals(code)){
            return true;
        }
        return false;
    }

    @Override
    public User findByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = userMapper.selectOne(queryWrapper);
        return user;
    }
}
